"""
   ┌─┐       ┌─┐ + +
┌──┘ ┴───────┘ ┴──┐++
│                 │
│       ───       │++ + + +
███████───███████ │+
│                 │+
│       ─┴─       │
│                 │
└───┐         ┌───┘
    │         │
    │         │   + +
    │         │
    │         └──────────────┐
    │                        │
    │                        ├─┐
    │                        ┌─┘
    │                        │
    └─┐  ┐  ┌───────┬──┐  ┌──┘  + + + +
      │ ─┤ ─┤       │ ─┤ ─┤
      └──┴──┘       └──┴──┘  + + + +
             神兽保佑
            代码无BUG!
# 更新xueqiu数据表中所有公司的2020年的一季度报和中报
"""
import time

import pymysql
import requests
from fake_useragent import UserAgent
import random


class Update_y1():
    def __init__(self):
        self.db = pymysql.connect(
            "127.0.0.1", "root", "123456", "hc", charset='utf8'
        )
        self.cur = self.db.cursor()
        self.headers = {
            'User-Agent': UserAgent().ie,
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Host": "stock.xueqiu.com",
            "Pragma": "no-cache",
            "Sec-Fetch-Mode": "navigate",
            "Sec-Fetch-Site": "none",
            "Sec-Fetch-User": "?1",
            "Upgrade-Insecure-Requests": "1",
            "Cookie": "device_id=66c9ce413d8d7cb2336815ac6a38fd0d; s=c111ybndx0; xq_a_token=3242a6863ac15761c18a8469b89065b03bd5e164; xqat=3242a6863ac15761c18a8469b89065b03bd5e164; xq_r_token=729679220e12a2fbd19b15c94e6b7624c5ea8702; xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOi0xLCJpc3MiOiJ1YyIsImV4cCI6MTYwNDgwMzAzMSwiY3RtIjoxNjAyMjQxNTUxOTk1LCJjaWQiOiJkOWQwbjRBWnVwIn0.A7T2psev7vxcvYgD8XjFdhkN4CYElre_cFdjhcfmGql0FTQrVCMxGQw60XCaEs0Yx09LfqByuOlSKeh2MIqWjMYvz9i7LvuqreBtMqTR1UnRZX9uolIY6ufxYAX1Ic5MCj8jvtiiMc0zfRWkLW1J471v8BJEaZNl_6qGEvNKEXUA8vWoJPz7Y5k5-7HL7u53wf19r1tr4fz4G3DhGwuiMxV0_2V9i_Xbb810gKPO6nPHOWaeuFTOB2AsLIL916fqeC4A9jSPHl5PqxYqkmPc_5P10bGZTkpWjmn0C0sdpCTyl6V_ROycu-mf9E_cXltoPqH54zHxsNri15dySAEMJw; u=111602241594487; Hm_lvt_1db88642e346389874251b5a1eded6e3={}; Hm_lpvt_1db88642e346389874251b5a1eded6e3={}".format(
                str(time.time()).split(".")[:10], str(time.time()).split(".")[:10])
        }
        self.url = "https://stock.xueqiu.com/v5/stock/finance/cn/{}.json?symbol={}&type={}&is_detail=true&count=5"
        self.ticker = []

    def get_company(self):
        sql_sel = "select company from xueqiu"
        self.cur.execute(sql_sel)
        for ticker in self.cur.fetchall():
            self.ticker.append(ticker[0])

    def get_json(self, url, symbol, q):
        # try:
        #     json_data = requests.get(self.url.format(url, "SH" + symbol), headers=self.headers).json()
        #     if not json_data["data"]:
        #         pass
        # except:
        #     return
        # if not json_data["data"]["list"]:
        #     json_data = requests.get(self.url.format(url, "SZ" + symbol), headers=self.headers).json()
        #     symbol = "SZ" + symbol
        # else:
        #     symbol = "SH" + symbol

        json_data = requests.get(self.url.format(url, symbol, q), headers=self.headers).json()
        report_type = ""
        if q == "Q1":
            report_type = "一季报"
        elif q == "Q2":
            report_type = "中报"
        elif q == "Q3":
            report_typ = "三季报"
        elif q == "Q4":
            report_type = "年报"
        financials = ""
        if url == "income":
            financials = "利润表"
        elif url == "balance":
            financials = "负债表"
        elif url == "cash_flow":
            financials = "资金流量表"
        for info in json_data["data"]["list"]:
            if info["report_name"] == "2020" + report_type:
                for i in info:
                    if i == "report_date" or i == "report_name" or i == "ctime":
                        continue
                    if info[i][0]:
                        y_0 = info[i][0]
                    else:
                        y_0 = 0
                    ins_sql='insert into xueqiu_data(company,report_type,financials,item,y_0) values ("%s","%s","%s","%s","%s")' % (symbol, report_type, financials, i,y_0)
                    self.cur.execute(ins_sql)
                    self.db.commit()
                    print("ins", symbol, i)

    def port(self, number):
        for i in ["income", "balance", "cash_flow"]:
            for q in ["Q1", "Q2"]:
                self.get_json(i, number, q)

    def run(self):
        self.get_company()
        for i in self.ticker:
            # for i in ("SZ002415", "SZ002594"):
            # 这个是防过快爬取，导致封停，如果感觉爬取慢可以注释掉
            time.sleep(random.randint(10, 20) / 10)
            self.port(i)


if __name__ == '__main__':
    up = Update_y1()
    up.run()
